import React, { useState, useRef } from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { CopyIcon, CheckIcon, FoldIcon, UnfoldIcon, CodeIcon } from "./Icons";

interface CodeBlockProps {
  language: string;
  value: string;
  className?: string;
}

/**
 * 增强的代码块组件
 *
 * 功能：
 * 1. 左上角显示代码语言
 * 2. 右上角显示折叠和复制按钮
 * 3. 代码折叠后显示折叠的行数
 * 4. 点击复制按钮复制代码
 */
const CodeBlock: React.FC<CodeBlockProps> = ({
  language,
  value,
  className,
}) => {
  const [isFolded, setIsFolded] = useState(false);
  const [isCopied, setIsCopied] = useState(false);
  const codeRef = useRef<HTMLDivElement>(null);

  // 计算代码行数
  const lineCount = value.split("\n").length;

  // 如果折叠，只显示前3行代码
  const displayedCode =
    isFolded && lineCount > 4
      ? value.split("\n").slice(0, 3).join("\n")
      : value;

  // 折叠的行数
  const foldedLines = lineCount - 3;

  // 复制代码到剪贴板
  const handleCopy = () => {
    navigator.clipboard.writeText(value).then(() => {
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    });
  };

  // 切换折叠状态
  const toggleFold = () => {
    setIsFolded(!isFolded);
  };

  // 只有当代码行数大于4行时才显示折叠按钮
  const showFoldButton = lineCount > 4;

  return (
    <div className="relative group rounded-md overflow-hidden my-4 bg-[#282c34] border border-gray-700 dark:border-gray-600">
      {/* 顶部工具栏 */}
      <div className="flex justify-between items-center px-4 py-2 bg-gray-800 border-b border-gray-700 text-gray-300">
        {/* 左侧语言标签 */}
        <div className="flex items-center space-x-2">
          <CodeIcon className="w-4 h-4" />
          <span className="text-xs font-mono">{language}</span>
        </div>

        {/* 右侧操作按钮 */}
        <div className="flex space-x-3">
          {/* 折叠按钮 - 只在代码行数大于4时显示 */}
          {showFoldButton && (
            <button
              onClick={toggleFold}
              className="text-gray-400 hover:text-white flex items-center space-x-1"
              title={isFolded ? "展开" : "折叠"}
            >
              {isFolded ? <UnfoldIcon /> : <FoldIcon />}
              <span className="text-xs">{isFolded ? "展开" : "折叠"}</span>
            </button>
          )}

          {/* 复制按钮 */}
          <button
            onClick={handleCopy}
            className="text-gray-400 hover:text-white flex items-center space-x-1"
            title={isCopied ? "已复制" : "复制"}
          >
            {isCopied ? <CheckIcon className="text-green-500" /> : <CopyIcon />}
            <span className="text-xs">{isCopied ? "已复制" : "复制"}</span>
          </button>
        </div>
      </div>

      {/* 代码高亮区域 */}
      <div ref={codeRef} className="relative">
        {/* @ts-expect-error - oneDark样式实际可用 */}
        <SyntaxHighlighter
          language={language}
          style={oneDark}
          className={className}
          customStyle={{
            margin: 0,
            padding: "1rem",
            fontSize: "0.9rem",
            borderRadius: 0,
          }}
          showLineNumbers={true}
        >
          {displayedCode}
        </SyntaxHighlighter>
      </div>

      {/* 折叠提示 */}
      {isFolded && foldedLines > 0 && (
        <div
          className="bg-gray-700 text-gray-300 text-center py-2 cursor-pointer hover:bg-gray-600 flex items-center justify-center space-x-2"
          onClick={toggleFold}
        >
          <UnfoldIcon className="w-4 h-4" />
          <span>还有 {foldedLines} 行被折叠 (点击展开)</span>
        </div>
      )}
    </div>
  );
};

export default CodeBlock;
